// cloudfunctions/createOrder/index.js
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

// 云函数入口
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()

    try {
        // 校验 cloud.payment 对象是否存在
        if (!cloud.payment) {
            console.error('cloud.payment 对象未定义')
            return {
                success: false,
                message: '支付功能未初始化，请检查云开发环境配置'
            }
        }
        // 校验参数
        const {
            goodsId,
            goodsName,
            price,
            count = 1,
            addressId
        } = event

        if (!goodsId || !goodsName || !price) {
            return {
                success: false,
                message: '商品信息不完整'
            }
        }

        // 生成订单号
        const outTradeNo = `WX${Date.now()}${Math.floor(Math.random() * 1000)}`

        // 调用云开发支付API统一下单（金额单位：分）
        const paymentResult = await cloud.payment.unifiedOrder({
            body: goodsName, // 商品描述
            outTradeNo: outTradeNo, // 商户订单号
            totalFee: Math.floor(price * 100), // 金额（分）
            spbillCreateIp: wxContext.CLIENTIP, // 客户端IP
            tradeType: 'JSAPI', // 交易类型
            envId: cloud.DYNAMIC_CURRENT_ENV, // 当前云环境ID
            functionName: 'payNotify', // 支付回调云函数
            openid: wxContext.OPENID,
        })

        // 保存订单到数据库
        const orderData = {
            goodsId,
            goodsName,
            price,
            count,
            addressId,
            outTradeNo,
            buyerId: wxContext.OPENID,
            status: '未支付',
            createTime: db.serverDate(),
            paymentResult
        }

        const orderRes = await db.collection('orders').add({
            data: orderData
        })

        // 返回支付参数给前端
        return {
            success: true,
            orderId: orderRes._id,
            outTradeNo: outTradeNo,
            paymentParams: {
                timeStamp: paymentResult.timeStamp,
                nonceStr: paymentResult.nonceStr,
                package: `prepay_id=${paymentResult.prepayId}`,
                signType: 'MD5',
                paySign: paymentResult.paySign
            }
        }
    } catch (error) {
        console.error('创建订单失败:', error)
        return {
            success: false,
            message: error.message || '创建订单失败'
        }
    }
}